package com.hmdp.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * @Author: X_x
 * @Packaqe: com.hmdp.utils
 * @Project: hm-dianping
 * @name: RedisIdWorker
 * @Date: 2024/8/26  11:39
 */
/**
 * 全局唯一ID生成：基于Redis的自增长
 */
@Component
public class RedisIdWorker {
    /*
    开始时间戳
     */
    private static final long BEGIN_TIMESTAMP = 1724630400L;
    /*
    序列号的位数(32 bit)
     */
    private static final int COUNT_BITS = 32;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    //可以使用    @Resource     @Autowired 注入也可以使用构造函数注入
/*    public RedisIdWorker(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }*/

    //keyPrefix:key前缀用于区分不同的业务
    public long nextId(String keyPrefix){
        //1.生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timestamp = nowSecond - BEGIN_TIMESTAMP;
        //2.生成序列号
        //2.1获取当前日期，精确到天
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        //2.2自增长
        long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date);
        //3.拼接并返回
        //不以字符串的形式拼接
        return timestamp << COUNT_BITS | count;
        /**
         * 符号位（0）+时间戳（32 bit）+序列号（32 bit）
         *
         * "timestamp << COUNT_BITS | count" 位运算，时间戳向左移32位，空出来的位置是32位0，用或运算填充序列号就是原序列号
         */
    }


}